package com.ruoyi.project.buildexperiment.controller;

import com.mysql.cj.x.protobuf.MysqlxDatatypes;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.buildexperiment.domain.AddExperimentParam;
import com.ruoyi.project.buildexperiment.domain.ExperimentDto;
import com.ruoyi.project.buildexperiment.domain.ExperimentParam;
import com.ruoyi.project.buildexperiment.domain.LabDto;
import com.ruoyi.project.buildexperiment.service.BuildExperimentService;
import com.ruoyi.project.explorer.domain.Explorer;
import com.ruoyi.project.explorer.domain.ExplorerDto;
import com.ruoyi.project.explorer.service.IExplorerService;
import com.ruoyi.project.jiaowu.kaikeinqure.domain.TbKaikeInqure;
import com.ruoyi.project.jiaowu.kaikeinqure.service.ITbKaikeInqureService;
import com.ruoyi.project.jiaowu.term.domain.TbTerm;
import com.ruoyi.project.jiaowu.term.service.ITbTermService;
import com.ruoyi.project.jiaowu.totalcoursemain.domain.TbTotalCourseMain;
import com.ruoyi.project.jiaowu.totalcoursemain.service.ITbTotalCourseMainService;
import com.ruoyi.project.system.onlineWeb.domain.OnlineWeb;
import com.ruoyi.project.system.onlineWeb.service.IOnlineWebService;
import com.ruoyi.project.system.user.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.tomcat.jni.FileInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 【教师管理-新建实验】Controller
 * 
 * @author menghang
 * @date 2019-11-18
 */
@Controller
@RequestMapping("buildexperiment")
public class BuildExperimentController extends BaseController
{
    private String prefix = "system/buildexperiment";

    @Autowired
    private BuildExperimentService buildExperimentService;
    @Autowired
    private ITbTotalCourseMainService tbTotalCourseMainService;
    @Autowired
    private IExplorerService explorerService;
    @Autowired
    private IOnlineWebService iOnlineWebService;
    @Autowired
    private ITbKaikeInqureService iTbKaikeInqureService;

    @Autowired
    private ITbTermService iTbTermService;


    @RequiresPermissions("buildexperiment:view")
    @GetMapping()
    public String property()
    {
        return prefix + "/buildexperiment";
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("system:buildexperiment:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ExperimentParam experimentParam)
    {
        /**
         * 获取当前登录的教师id
         */
        experimentParam.setUserId(getSysUser().getUserId());
        startPage();
        List<ExperimentDto> experimentDtoList = buildExperimentService.selectBuildexperiment(experimentParam);
        return getDataTable(experimentDtoList);
    }

    /**
     * 进入新增实验室页面
     */
    @GetMapping("/add")
    @RequiresPermissions("system:labapprove:add")
    public String add(ModelMap mmap)
    {
        return prefix + "/add";
    }

    /**
     * 进入新增实验室页面
     */
    @GetMapping("/addPage")
    public String addPage(ModelMap mmap)
    {
        Long userId=getUserId();
        //查询用户已经预约的实验室    并且该实验室没有被关闭
        List<LabDto> labDtoList=buildExperimentService.selectLab(userId);
        /**
         * 教师添加实验时，所选课程即为自己的开课课程
         */
        TbKaikeInqure tbKaikeInqure = new TbKaikeInqure();
        tbKaikeInqure.setCourseTeacher(getSysUser().getLoginName());
        List<TbKaikeInqure> list = iTbKaikeInqureService.selectTbKaikeInqureList2(tbKaikeInqure);
        /**
         * 获取当前学期
         */
        Date date = new Date();
        List<TbTerm> tbTerms = iTbTermService.selectTbTermLists();
        Long stuYear = null;
        for(TbTerm tbTerm:tbTerms){
            if(tbTerm.getStartTime().getTime()<date.getTime() && tbTerm.getEndTime().getTime()>date.getTime()){
                stuYear = tbTerm.getId();
                break;
            }
        }
        //获取仅在开课期限内的开课信息
        for(int i=0;i<list.size();i++){
            if(!Long.valueOf(list.get(i).getStuTerm()).equals(stuYear)){
                list.remove(i);
                i--;
            }
        }
        Explorer explorer=new Explorer();
        //查询所选课程资源
        List<ExplorerDto> explors = explorerService.selectExplorerList(explorer);
        if(explors!=null){
            mmap.put("explors",explors);
        }
        if(labDtoList.size()>0){
            mmap.put("labList",labDtoList);
        }
        mmap.put("courseList",list);
        List<OnlineWeb> weblist= iOnlineWebService.selectOnlineWebList(null);
        mmap.put("weblist",weblist);
        return prefix + "/add";
    }


    /**
     * 新增教师实验室课程
     */
    @PostMapping("/addExperiment")
    @Log(title = "新增教师实验室课程", businessType = BusinessType.INSERT)
    @ResponseBody
    public AjaxResult addExperiment(AddExperimentParam experimentParam)
    {
        experimentParam.setUserId(getUserId());
        String message=experimentParam.getIdweb();
        if(StringUtils.isEmpty(message)){
            experimentParam.setOnlineId(null);
        }else{
            int index1=message.indexOf(",");
            int index2=message.lastIndexOf(",");
            Long value=Long.valueOf(message.substring(index1+1,index2));
            experimentParam.setOnlineId(value);
        }
        experimentParam.setUploadPath(null);
        //System.err.println(value);
        Long id=buildExperimentService.ifExits(experimentParam.getExperimentLabId());
        if(!StringUtils.isNull(id)){
             return AjaxResult.error("当前预约实验室已经布置实验，请发布或删除");
        }
        return buildExperimentService.insertExperiment(experimentParam);
        //return toAjax(true);
    }
    @GetMapping("/issue")
    @Log(title = "发布实验室课程", businessType = BusinessType.INSERT)
    @ResponseBody
    public AjaxResult issue(Long id)
    {
//        experimentParam.setUserId(getUserId());

        return toAjax(buildExperimentService.issue(id));

    }
    @GetMapping("/addcheck")
    @Log(title = "发布实验室课程", businessType = BusinessType.INSERT)
    @ResponseBody
    public AjaxResult addcheck()
    {
        Long userId=getUserId();
        //查询用户已经预约的实验室  并且实验室日期大于现在，且未被使用
        List<LabDto>labDtoList=buildExperimentService.selectLab(userId);
        if(labDtoList.size()==0){
            return error();
        }
        return success();
    }


    @GetMapping("/delete")
    @Log(title = "删除实验室课程", businessType = BusinessType.DELETE)
    @ResponseBody
    public AjaxResult delete(Long id)
    {
        return toAjax(buildExperimentService.deleteById(id));
    }

    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult deleteAll(String ids){
        //System.err.println(ids);
        //return toAjax(true);
        return toAjax(buildExperimentService.deletes(ids));
    }

    /**
     * 新增教师实验室课程
     */
    @PostMapping("/upload")
    @ResponseBody
    public void reload(MultipartFile file)
    {
        System.out.println(file);
    }


    @RequiresPermissions("system:labapprove:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap map){
        //System.err.println("id:"+id);
        ExperimentDto experimentDto=buildExperimentService.getExperimentDtoById(id);
        map.addAttribute("experimentDto",experimentDto);
        Long userId=getUserId();
        //查询用户已经预约的实验室
        List<LabDto> labDtoList=buildExperimentService.selectLab(userId);
        /**
         * 教师添加实验时，所选课程即为自己的开课课程
         */
        TbKaikeInqure tbKaikeInqure = new TbKaikeInqure();
        tbKaikeInqure.setCourseTeacher(getSysUser().getLoginName());
        List<TbKaikeInqure> list = iTbKaikeInqureService.selectTbKaikeInqureList2(tbKaikeInqure);
        /**
         * 获取当前学期
         */
        Date date = new Date();
        List<TbTerm> tbTerms = iTbTermService.selectTbTermLists();
        Long stuYear = null;
        for(TbTerm tbTerm:tbTerms){
            if(tbTerm.getStartTime().getTime()<date.getTime() && tbTerm.getEndTime().getTime()>date.getTime()){
                stuYear = tbTerm.getId();
                break;
            }
        }
        //获取仅在开课期限内的开课信息
        for(int i=0;i<list.size();i++){
            if(!Long.valueOf(list.get(i).getStuTerm()).equals(stuYear)){
                System.out.println(list.get(i));
                list.remove(i);
                i--;
            }
        }
        Explorer explorer ;
        List<ExplorerDto> explors;
        if(list.size()>0){
            explorer=new Explorer();
            /*explorer.setCourseId(list.get(0).getId());*/
            //查询所选课程资源
            explors = explorerService.selectExplorerList(explorer);
            if(explors!=null){
                map.put("explors",explors);
            }
        }
        if(labDtoList.size()>0){
            map.put("labList",labDtoList);
        }
        /**
         * 查詢資源分類的名稱即課程名
         */
        map.put("courseList",list);
        List<OnlineWeb> weblist= iOnlineWebService.selectOnlineWebList(null);
        map.put("weblist",weblist);
        return prefix+"/edit2";
    }


    /**
     * 修改保存
     */
    @PostMapping("/editList")
    @ResponseBody
    public AjaxResult editList(ExperimentDto experimentDto){
        //System.err.println(experimentDto);
        String message=experimentDto.getIdweb();
        if(StringUtils.isEmpty(message)){
            experimentDto.setOnlineId(null);
        }else{
            //System.err.println("你好"+message);
            int index1=message.indexOf(",");
            int index2=message.lastIndexOf(",");
            Long value=Long.valueOf(message.substring(index1+1,index2));
            experimentDto.setOnlineId(value);
        }
        experimentDto.setAccessoryPath(null);
        //System.err.println(value);
        //System.err.println("123:"+experimentDto);
        //当修改保存时，此实验实验表中数据改动，同时对应的已提交的该实验的信息也改动
        Long id=buildExperimentService.ifExits(experimentDto.getLabDateId().toString());
        /*if(StringUtils.isNull(id)){
            return AjaxResult.error("当前预约实验室已经布置实验，请发布或删除");
        }*/
        return toAjax(buildExperimentService.updateExperiment(experimentDto));
    }


    /**
     * 新增保存，当他有上传文件的时候
     * @param file
     * @param experimentParam
     * @return
     * @throws IOException
     */
    @PostMapping("/adddvadvd")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("file") MultipartFile file,AddExperimentParam experimentParam) throws IOException
    {
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        // 上传并返回新文件名称
        String fileName = null;
        try{
            fileName = FileUploadUtils.upload(filePath, file);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        //String fileName = FileUploadUtils.upload(filePath, file);
        //System.err.println(experimentParam);
        experimentParam.setUserId(getUserId());
        String message=experimentParam.getIdweb();
        if(StringUtils.isEmpty(message)){
            experimentParam.setOnlineId(null);
        }else{
            int index1=message.indexOf(",");
            int index2=message.lastIndexOf(",");
            Long value=Long.valueOf(message.substring(index1+1,index2));
            experimentParam.setOnlineId(value);
        }
        experimentParam.setUploadPath(fileName);
        Long id=buildExperimentService.ifExits(experimentParam.getExperimentLabId());
        if(!StringUtils.isNull(id)){
            return AjaxResult.error("当前预约实验室已经布置实验，请发布或删除");
        }
        //System.err.println(value);
        return buildExperimentService.insertExperiment(experimentParam);
    }


    /**
     * 修改保存，有文件上传时
     */
    @PostMapping("/editedit")
    @ResponseBody
    public AjaxResult editsave(@RequestParam("file") MultipartFile file,ExperimentDto experimentDto) throws IOException
    {
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = null;
        try{
            fileName = FileUploadUtils.upload(filePath, file);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        //System.err.println(experimentDto);
        String message=experimentDto.getIdweb();
        if(StringUtils.isEmpty(message)){
            experimentDto.setOnlineId(null);
        }else{
            int index1=message.indexOf(",");
            int index2=message.lastIndexOf(",");
            Long value=Long.valueOf(message.substring(index1+1,index2));
            experimentDto.setOnlineId(value);
        }
        //System.err.println(value);
        experimentDto.setAccessoryPath(fileName);
        Long id=buildExperimentService.ifExits(experimentDto.getLabDateId().toString());
        /*if(StringUtils.isNull(id)){
            return AjaxResult.error("当前预约实验室已经布置实验，请发布或删除");
        }*/
        return toAjax(buildExperimentService.updateExperiment(experimentDto));
    }

}
